package com.quan.weixin.wx.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quan.common.core.BaseController;
import com.quan.common.properties.WxConfigProperties;
import com.quan.mall.entity.MallUser;
import com.quan.mall.service.MallUserService;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@RestController
@RequestMapping("/wx/mall/user/oauth")
public class WxMallUserOauthController extends BaseController {
	
	@Autowired
	private WxConfigProperties wxConfigProperties;

	@Autowired
	private WxMpService wxMpService;

	@Autowired
	private MallUserService mallUserService;

	/**
	 * 网页授权，获取用户详细信息，需要用户授权
	 * 
	 * @param state
	 */
	@GetMapping(value = "/oauth_process_userinfo")
	public void oAuthProcessUserInfo(String state) {
		logger.debug("-----------------------微信网页授权，引导用户到授权页面----------------------------");

		try {
			String getCodeUrl = this.wxMpService.oauth2buildAuthorizationUrl(
					this.wxConfigProperties.getOauthCallbackUrl(), 
					WxConsts.OAuth2Scope.SNSAPI_USERINFO, 
					state);
			this.response.sendRedirect(getCodeUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 网页授权回调处理方法
	 * 
	 * @return
	 */
	@GetMapping(value = "/oauth_callback_userinfo")
	public void OAuthCallbackUserInfo() {
		logger.debug("-----------------------微信网页授权，回调处理----------------------------");

		try {
			// 接收微信传回的code参数
			String code = request.getParameter("code");
			// 接收用户从微信客户端传来的参数（比如用户传的是一个业务URL页面地址，处理完以下业务后直接跳转到该业务URL地址）
			//String state = request.getParameter("state");

			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);

			WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);

			MallUser oauthUser = this.mallUserService.findByOpenId(wxMpUser.getOpenId());
			if (null == oauthUser) {
				// 将授权用户存储到数据库
				MallUser user = new MallUser();
				user.setOpenid(wxMpUser.getOpenId());
				user.setHeadimgurl(wxMpUser.getHeadImgUrl());
				user.setNickname(wxMpUser.getNickname());
				user.setSex(wxMpUser.getSex());
				this.mallUserService.insertSelective(user);
			}

			String toUrl = this.wxConfigProperties.getOauthBizPageUrl() + "?openid=" + wxMpUser.getOpenId();
			this.response.sendRedirect(toUrl);

			logger.debug("用户信息：{}", wxMpUser.toString());
			logger.debug("跳转地址：{}", toUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
